const fs = require('fs')
const path = require('path')
const { prompt } = require('inquirer')
const { execSync } = require('child_process')

const resolve = (file) => path.resolve(__dirname, file)
let entries = JSON.parse(fs.readFileSync(resolve('./build/config.entries.json')), 'utf-8')
entries.push({ value: 'libs', name: 'Libs' })
entries = entries.map(({ value, name }) => {
  if (value === 'all') return { value, name }
  return { value, name: `${value} (${name})` }
})

prompt([
  {
    type: 'list',
    name: 'mode',
    message: '请选择打包环境：',
    choices: [{ value: 'prod', name: '正式环境' }, { value: 'test', name: '测试环境' }],
  },
  {
    type: 'list',
    name: 'entry',
    message: '选择打包模块：',
    choices: entries,
  },
]).then((answers) => {
  const { entry, mode } = answers
  const env = Object.create(process.env)
  env.BUILD_MODE = mode

  if (entry === 'libs') {
    execSync('npm run build:libs', { env, stdio: 'inherit' })
  } else {
    env.VUE_APP_ENTRY = entry
    execSync('npm run build', { env, stdio: 'inherit' })
  }
})
